import { Route } from '@/interfaces/route';
import NoAuthentication from '@/views/error/401';
import NotFound from '@/views/error/404';
import Login from '@/views/login';
import { Suspense } from 'react';
import { Navigate, useRoutes } from 'react-router-dom';

const permissionRouters = import.meta.globEager('./modules/*.tsx');

const permissionRoutes: Route[] = [];
Object.keys(permissionRouters).forEach((item) => {
  Object.keys(permissionRouters[item]).forEach((key: any) => {
    permissionRoutes.push(...permissionRouters[item][key]);
  });
});

const staticRoutes: Route[] = [
  ...permissionRoutes,
  {
    path: '/',
    element: <Navigate to="home" />
  },
  {
    path: '/login',
    element: <Login />,
    meta: {
      title: '登录页'
    }
  },
  {
    path: '/404',
    element: <NotFound />
  },
  {
    path: '/401',
    element: <NoAuthentication />
  },
  {
    path: '*',
    element: <Navigate to="404" />
  }
];

function recursionRoutes(routes: Route[]) {
  routes.forEach((route) => {
    if (route.component) {
      route.element = (
        <Suspense>
          <route.component />
        </Suspense>
      );
    }
    route.children && recursionRoutes(route.children);
  });
}

recursionRoutes(staticRoutes);

export const menuRoutes: Route[] = staticRoutes.reduce((acc, route): Route[] => {
  // 过滤Layout
  if (!route.path && route.children) {
    acc.push(...route.children);
  }
  return acc;
}, [] as Route[]);

export const whiteList = ['/login', '/404', '/401'];

export default function Routes() {
  return useRoutes([...staticRoutes]);
}
